package com.iot.manage.biz.controller;

import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import java.util.List;

import javax.validation.Valid;

import org.springframework.web.bind.annotation.*;

import com.iot.common.core.exception.ModelException;
import com.iot.common.core.util.R;
import com.iot.common.core.util.UuidUtil;
import com.iot.common.security.annotation.SecurityAuthorization;
import com.iot.manage.api.domain.SysMenu;
import com.iot.manage.api.domain.SysRoleMenu;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

@RestController
@RequiredArgsConstructor
@RequestMapping("/menu")
@Api(value = "menu", tags = "用户管理模块")
public class MenuController {

	@Setter
	private Throwable cause;

	@SecurityAuthorization
	@GetMapping(value = { "/list" }, produces = "application/json; charset=utf-8")
	public R<List<SysMenu>> list(@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
			@RequestParam(name = "rootId", required = false, defaultValue = "-1") String rootId) throws Exception {
		List<SysMenu> menus = SysMenu.dao.find("SELECT T.*,(CASE  WHEN (SELECT COUNT(ID) AS COUNT FROM "
				+ SysMenu.TABLE_NAME + " WHERE PARENTID=T.ID)>0 THEN 1 ELSE  0 END )  as hasChildren FROM "
				+ SysMenu.TABLE_NAME + " T WHERE T.PARENTID=? ORDER BY T.SORT ASC ", rootId);
		return R.ok(menus);
	}
	
	@SecurityAuthorization
    @RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<SysMenu> save(@Valid SysMenu sysMenu) {
		if (sysMenu == null) {
			throw new ModelException("菜单对象不可以为空！");
		}
		if (StrKit.isBlank(sysMenu.getId())) {
			sysMenu.setId(UuidUtil.getUUID());
			if (sysMenu.save()) {
				return R.ok(sysMenu);
			}
		} else {
			if (sysMenu.update()) {
				return R.ok(sysMenu);
			}
		}
		return R.failed();
	}
	

	@SecurityAuthorization
	@GetMapping(value = { "/deleteById" }, produces = "application/json; charset=utf-8")
	public R<Boolean> deleteById(@RequestParam(name = "id", required = true) String id) throws Exception {
		if(Db.queryDouble("SELECT COUNT(*) FROM "+SysMenu.TABLE_NAME+" WHERE PARENTID=?",id)>0) {
			return R.failed("有子节点，不允许删除！", false);
		}
		if (SysMenu.dao.deleteById(id)) {
			Db.delete("DELETE FROM "+SysRoleMenu.TABLE_NAME+" WHERE MENU_ID=? ",id);
			return R.ok(true);
		} else {
			return R.failed(false);
		}
	}

}
